<script setup lang="ts">
import { ref } from 'vue'
import useApi from '../useApi';
import msgModal from '../components/msgModal.vue'
// 引入CustomConfirm组件
import CustomConfirm from './CustomConfirm.vue'
import { onMounted } from 'vue';
// 引入NumericKeyboard组件
import NumericKeyboard from './NumericKeyboard.vue'

onMounted(() => {
	if(userPhoneFromLocal != null && userPhoneFromLocal !== 'null' && userPhoneFromLocal !== ''){
		phoneNumSearch.value = userPhoneFromLocal;
	}
	searchOrderInfo();
});

const msgModalRef = ref(msgModal);
let userPhoneFromLocal:any = localStorage.getItem('userPhone') || '';
console.log(userPhoneFromLocal);
let phoneNumSearch = ref(''),memberSearchShow = ref(false),startDate = ref(''),endDate = ref(''),orderList:any = ref([]); // 修改这里，将空对象改为空数组
// 添加分页相关变量
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);

let orderId = ref(0);
let orderDetailShow = ref(false),orderInfoDetail:any = ref({}),confirmVisible = ref(false),msgTitle = ref(''),thisOrderId = ref(0),orderNum = ref(''),inputType = ref(1),orderInfo:any = ref({});

// 获取状态样式类函数
const getStatusClass = (status) => {
	switch(status) {
		case 1: return 'status-pending';
		case 2: return 'status-success';
		case 3: return 'status-refund';
		default: return '';
	}
}

const showModal = (title,times=1000) => {
	if(msgModalRef.value){
		msgModalRef.value.openMsg(title,times);
	}
}

// 添加数字键盘相关方法
// 处理数字键盘输入
const handleKeyboardInput = (value) => {
    if(inputType.value == 1){
        phoneNumSearch.value = value;
    }else{
        orderNum.value = value;
    }
}

// 处理数字键盘确认
const handleKeyboardConfirm = (value) => {
    if(inputType.value == 1){
        phoneNumSearch.value = value;
    }else{
        orderNum.value = value;
    }
    memberSearchShow.value = false;
}

// 处理数字键盘取消
const handleKeyboardCancel = () => {
    memberSearchShow.value = false;
}

// 注释掉旧的键盘输入方法
// const inputKeyNum =  (event) =>  {
// 	if(inputType.value == 1){
// 		phoneNumSearch.value = phoneNumSearch.value+event.target.innerText;
// 	}else{
// 		orderNum.value = orderNum.value+event.target.innerText;
// 	}
// }
// const deleteKeyNum =  () =>  {
// 	if(inputType.value == 1){
// 		phoneNumSearch.value = phoneNumSearch.value.substring(0,phoneNumSearch.value.length-1);
// 	}else{
// 		orderNum.value = orderNum.value.substring(0,orderNum.value.length-1);
// 	}
// }
// const clearKeyNum =  () =>  {
// 	if(inputType.value == 1){
// 		phoneNumSearch.value = '';
// 	}else{
// 		orderNum.value = '';
// 	}
// }
const orderDetail = async(id) => {
	orderId.value = id;
	orderDetailShow.value = true;
	let bodyData = ref({});
    bodyData.value = {
        id:id
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    let res:any = await useApi('index/getOrderDetail',options); 
    if(res.code == 1){
        orderInfoDetail.value = res.data;
    }else{
        showModal(res.msg);
    }
	res = await useApi('index/getOrderInfo',options); 
	orderInfo.value = res.data;
}
const searchOrderInfo = () =>{
	// if(phoneNumSearch.value == '' && orderNum.value == ''){
	// 	showModal('请输入手机号或订单号',1000);
	// 	return;
	// }
	getOrderInfo();
}

const getOrderInfo = async()=>{
    let bodyData = ref({});
    bodyData.value = {
        phone:phoneNumSearch.value,
		start:startDate.value,
		end:endDate.value,
		orderNum:orderNum.value,
        page: currentPage.value,
        pageSize: pageSize.value
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
    let res:any = await useApi('index/getUserOrderForPage',options); 
    if(res.code == 1){
        orderList.value = res.data.data || [];
        total.value = res.data.count || 0;
		console.log('订单数据:', orderList.value); // 添加日志，查看数据是否正确获取
    }else{
        showModal(res.msg);
    }
}

// 添加分页变化处理函数
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    getOrderInfo();
}

const orderReserve = (id) =>{
	// 使用CustomConfirm组件替代原来的msgTitleShow
	confirmVisible.value = true;
	thisOrderId.value = id;
	msgTitle.value = '确定要退单吗？';
}

// 确认退单
const confirmRefund = async() => {
	let bodyData = ref({});
    bodyData.value = {
        id:thisOrderId.value
    }
    const options:any = {
        headers: {
            "Content-Type": "application/json",
            "token":localStorage.getItem('token')
        },
        method: "POST",
        body:JSON.stringify(bodyData.value)
    };
	showModal('退货中，请稍等',10000);
    let res:any = await useApi('index/orderReverse',options); 
    if(res.code == 1){
		showModal('退款成功');
		confirmVisible.value = false;
        getOrderInfo();
    }else{
		confirmVisible.value = false;
        showModal(res.msg);
    }
}

// 取消退单
const cancelRefund = () => {
	confirmVisible.value = false;
}
const printData = async() =>{
	let data = orderInfo.value;
	window.electron.ipcRenderer.send('print',JSON.stringify(data.detail),localStorage.getItem('title'),data.allNum,data.allPrice,data.orderNumber,data.paytype,data.userId,data.balanceEndNum,data.created_at,data.userPhone);
    
}
</script>

<template>
	<msgModal ref="msgModalRef"/>
	<main class="ordermain">
		<div class="order">
			<!-- 使用CustomConfirm组件替换原来的退单确认弹框 -->
			<CustomConfirm 
				:visible="confirmVisible"
				title="退单确认"
				:message="msgTitle"
				confirm-text="确定"
				cancel-text="取消"
				@confirm="confirmRefund"
				@cancel="cancelRefund"
			/>
			
			<!-- 使用NumericKeyboard组件替换原来的数字键盘 -->
			<NumericKeyboard
				v-model:visible="memberSearchShow"
				:initial-value="inputType == 1 ? phoneNumSearch : orderNum"
				:title="inputType == 1 ? '请输入手机号码' : '请输入订单号'"
				@input="handleKeyboardInput"
				@confirm="handleKeyboardConfirm"
				@cancel="handleKeyboardCancel"
			/>
			
			<!-- 注释掉原来的数字键盘弹框 -->
			<!-- <Transition name="memberRechargeSearch">
				<div class="memberRechargeSearchModel" v-show='memberSearchShow'>
					<div class="modelInfo">
						<div class="numKey">
							<button @click="inputKeyNum" class="key">1</button>
							<button @click="inputKeyNum" class="key">2</button>
							<button @click="inputKeyNum" class="key">3</button>
							<button @click="inputKeyNum" class="key">4</button>
							<button @click="inputKeyNum" class="key">5</button>
							<button @click="inputKeyNum" class="key">6</button>
							<button @click="inputKeyNum" class="key">7</button>
							<button @click="inputKeyNum" class="key">8</button>
							<button @click="inputKeyNum" class="key">9</button>
							<button @click="clearKeyNum" class="key">清空</button>
							<button @click="inputKeyNum" class="key">0</button>
							<button @click="deleteKeyNum" class="key">删除</button>
						</div>
						<div class="footer">
							<el-button @click="memberSearchShow = false" class="cancel">确定</el-button>
							<el-button @click="memberSearchShow = false" class="cancel">取消</el-button>
						</div>
					</div>
				</div>
			</Transition> -->
			
			<!-- 订单详情弹框优化 -->
			<Transition name="orderDetailModel">
				<div class="orderDetailModel" v-show='orderDetailShow'>
					<div class="modelInfo detail-dialog">
						<div class="detail-header">
							<h3>订单详情</h3>
							<el-button @click="orderDetailShow = false" class="close-btn" type="text">
								<i class="el-icon-close"></i>
							</el-button>
						</div>
						<div class="detail-content">
							<div class="order-info-section">
								<h4>订单信息</h4>
								<div class="order-info-grid">
									<div class="info-item">
										<span class="label">订单号:</span>
										<span class="value">{{orderInfo.orderNumber}}</span>
									</div>
									<div class="info-item">
										<span class="label">状态:</span>
										<span class="value status" v-bind:class="{  'fail': orderInfo.status == 1,'success': orderInfo.status == 2,'refound': orderInfo.status == 3 }">{{orderInfo.statusTitle}}</span>
									</div>
									<div class="info-item">
										<span class="label">时间:</span>
										<span class="value">{{orderInfo.created_at}}</span>
									</div>
									<div class="info-item">
										<span class="label">付款方式:</span>
										<span class="value">{{orderInfo.payTypeTitle}}</span>
									</div>
									<div class="info-item">
										<span class="label">总量:</span>
										<span class="value">{{orderInfo.allNum}}</span>
									</div>
									<div class="info-item">
										<span class="label">总价:</span>
										<span class="value price">￥{{orderInfo.allPrice}}</span>
									</div>
									<div class="info-item">
										<span class="label">余额支付:</span>
										<span class="value">￥{{orderInfo.balanceNum}}</span>
									</div>
									<div class="info-item">
										<span class="label">现金支付:</span>
										<span class="value">￥{{orderInfo.moneyNum}}</span>
									</div>
									<div class="info-item full-width">
										<span class="label">备注:</span>
										<span class="value">{{orderInfo.remark}}</span>
									</div>
									<div class="info-item full-width">
										<span class="label">用户资料:</span>
										<span class="value">{{orderInfo.userinfo}}</span>
									</div>
								</div>
							</div>
							
							<div class="product-section">
								<h4>商品信息</h4>
								<table class="detail-table">
									<thead>
										<tr>
											<th class="product-name">商品名称</th>
											<th class="product-price">单价</th>
											<th class="product-quantity">数量</th>
											<th class="product-total">总价</th>
										</tr>
									</thead>
									<tbody>
										<tr v-for="(data,index) in orderInfoDetail" :key="index">
											<td class="product-name">{{ data.goodName }}</td>
											<td class="product-price">￥{{ data.price }}</td>
											<td class="product-quantity">× {{ data.allNum }}</td>
											<td class="product-total">￥{{ data.allPrice }}</td>
										</tr>
									</tbody>
								</table>
							</div>
						</div>
						<div class="detail-footer">
							<el-button @click="printData()" type="success" class="print-btn">打印</el-button>
							<el-button @click="orderDetailShow = false" type="info">关闭</el-button>
						</div>
					</div>
				</div>
			</Transition>
			
			<div class="page-header">
				<h2>订单管理</h2>
			</div>
			
			<div class="ordertop">
				<div class="search-container">
					<!-- 修改手机号输入框 -->
					<div class="search-input-group">
						<span class="search-icon">🔍</span>
						<input 
							class="search-input" 
							@click="memberSearchShow = true; inputType = 1;" 
							v-model="phoneNumSearch" 
							placeholder="请输入手机号查询"
							readonly
						>
					</div>
					
					<!-- 修改订单号输入框 -->
					<div class="search-input-group">
						<span class="search-icon">🔍</span>
						<input 
							class="search-input" 
							@click="memberSearchShow = true; inputType = 2;" 
							v-model="orderNum" 
							placeholder="请输入订单号查询"
							readonly
						>
					</div>
					
					<!-- 保留日期选择器 -->
					<el-date-picker
						class="dataPicker"
						v-model="startDate"
						type="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						placeholder="开始日期">
					</el-date-picker>
					<el-date-picker
						class="dataPicker"
						v-model="endDate"
						type="date"
						format="YYYY-MM-DD"
						value-format="YYYY-MM-DD"
						placeholder="结束日期">
					</el-date-picker>
					
					<!-- 修改查询按钮 -->
					<button @click="searchOrderInfo" class="search-btn">查询</button>
				</div>
			</div>
			
			<div class="table-container">
				<table class="orderinfo">
					<thead class="headerinfo">
						<tr class="tr">
							<th class="title">消费门店</th>
							<th class="title">会员</th>
							<th class="title">数量</th>
							<th class="title">金额</th>
							<th class="title">赠送</th>
							<th class="title">时间</th>
							<th class="title">状态</th>
							<th class="operation">操作</th>
						</tr>
					</thead>
					<tbody class="forminfo">
						<tr class="tr" v-for="(data,index) in orderList" :key="index">
							<td class="title">{{ data.title }}</td>
							<td class="title">{{ data.userPhone }}</td>
							<td class="title">{{ data.allNum }}</td>
							<td class="title price">￥{{ data.allPrice }}</td>
							<td class="title">{{ data.giveMoneyNum }}</td>
							<td class="title">{{ data.created_at }}</td>
							<td class="title">
								<span class="status-tag" :class="getStatusClass(data.status)">{{ data.statusTitle }}</span>
							</td>
							<td class="operation">
								<el-button @click="orderDetail(data.id)" type="info" size="small" class="action-button">详情</el-button>
								<el-button @click="orderReserve(data.id)" v-if="data.status == 2" type="danger" size="small" class="action-button">退单</el-button>
							</td>
						</tr>
						<tr v-if="!orderList || orderList.length === 0">
							<td colspan="8" class="empty-data">暂无数据</td>
						</tr>
					</tbody>
				</table>
			</div>
			
			<!-- 分页组件 -->
			<div class="pagination-container">
				<el-pagination
					background
					layout="total, prev, pager, next"
					:total="total"
					:page-size="pageSize"
					:current-page="currentPage"
					:prev-text="'上一页'"
					:next-text="'下一页'"
					:pager-count="7"
					@current-change="handleCurrentChange"
				>
					<template #total>
						总数：{{ total }}
					</template>
				</el-pagination>
			</div>
		</div>
    </main>
</template>

<!-- 删除这里的第二个script标签及其内容 -->

<style scoped>
.ordermain {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.order {
  width: 100%;
}

.page-header h2 {
  color: #303133;
  font-weight: 500;
  margin: 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

/* 修改搜索容器样式 */
.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  flex-wrap: wrap;
  gap: 10px;
}

/* 添加搜索输入框组样式 */
.search-input-group {
  position: relative;
  width: 200px;
}

.search-icon {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.search-input {
  width: 100%;
  height: 40px;
  padding: 0 15px 0 40px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  font-size: 14px;
  transition: all 0.3s;
}

.search-input:focus {
  border-color: #409EFF;
  outline: none;
}

.search-input::placeholder {
  color: #c0c4cc;
}

/* 添加搜索按钮样式 */
.search-btn {
  height: 40px;
  padding: 0 20px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.search-btn:hover {
  background-color: #66b1ff;
}

.search-btn:active {
  background-color: #3a8ee6;
}

/* 保留日期选择器样式 */
.dataPicker {
  width: 200px;
  height: 40px;
}

.table-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.orderinfo {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.headerinfo {
  background-color: #f5f7fa;
}

.headerinfo .tr th {
  font-weight: bold;
  color: #606266;
  padding: 1px 15px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}

.forminfo .tr .title {
  padding: 1px 15px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  text-align: center;
}

.forminfo .tr:hover {
  background-color: #f5f7fa;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-pending {
  background-color: #e6a23c;
  color: #fff;
}

.status-success {
  background-color: #67c23a;
  color: #fff;
}

.status-refund {
  background-color: #f56c6c;
  color: #fff;
}

.action-button {
  margin: 0 5px;
}

.operation {
  white-space: nowrap;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 订单详情弹窗样式 */
.orderDetailModel {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.detail-dialog {
  background-color: #fff;
  border-radius: 8px;
  width: 90%;
  max-width: 1000px;
  max-height: 90vh;
  overflow: hidden;
  padding: 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}

.detail-header {
  background-color: #409eff;
  color: white;
  padding: 15px 20px;
  text-align: center;
  position: relative;
  border-bottom: 1px solid #ebeef5;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.close-btn {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: white;
  font-size: 20px;
}

.detail-content {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}
.page-header {
    margin-bottom: 5px;
}
.order-info-section, .product-section {
  margin-bottom: 20px;
}

.order-info-section h4, .product-section h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-weight: 500;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.order-info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
}

.full-width {
  grid-column: span 2;
}

.label {
  color: #909399;
  margin-right: 10px;
  min-width: 80px;
}

.value {
  color: #606266;
}

.value.status.success {
  color: #67c23a;
}

.value.status.fail {
  color: #e6a23c;
}

.value.status.refound {
  color: #f56c6c;
}

.value.price {
  color: #f56c6c;
  font-weight: 500;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.detail-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  padding: 12px 8px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}

.detail-table td {
  padding: 12px 8px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
}

.product-name {
  width: 40%;
  text-align: left !important;
}

.product-price, 
.product-quantity, 
.product-total {
  width: 20%;
}

.detail-footer {
  padding: 15px 20px;
  text-align: center;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.print-btn {
  margin-right: 10px;
}

/* 确认弹框样式 */
.confirm-dialog {
  width: 400px;
  padding: 0;
  border-radius: 8px;
  overflow: hidden;
}

.confirm-header {
  background-color: #f56c6c;
  color: white;
  padding: 15px 20px;
  text-align: center;
}

.confirm-header h3 {
  margin: 0;
  font-size: 18px;
}

.confirm-content {
  padding: 30px 20px;
  text-align: center;
  font-size: 16px;
}

.confirm-footer {
  padding: 10px 20px 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 数字键盘样式 */
.numKey {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin-bottom: 20px;
}

.key {
  padding: 15px;
  font-size: 18px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.key:hover {
  background-color: #f5f7fa;
}

.key:active {
  background-color: #e6e6e6;
}

/* 过渡动画 */
.msgTitlefade-enter-active,
.msgTitlefade-leave-active,
.memberRechargeSearch-enter-active,
.memberRechargeSearch-leave-active,
.orderDetailModel-enter-active,
.orderDetailModel-leave-active {
  transition: opacity 0.3s ease;
}

.msgTitlefade-enter-from,
.msgTitlefade-leave-to,
.memberRechargeSearch-enter-from,
.memberRechargeSearch-leave-to,
.orderDetailModel-enter-from,
.orderDetailModel-leave-to {
  opacity: 0;
}
</style>